﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommunity.Documents;
using XCommunity.Data;

namespace XCommunity.Frames
{
  /// <summary>
  /// 实体版面，版面是一个话题的集合
  /// </summary>
  public class PracticalBoardFrame : BoardFrame
  {

    public PracticalBoardFrame( FrameService service, string id )
      : base( service, id )
    {
    }



    /// <summary>
    /// 发布一个话题
    /// </summary>
    /// <param name="document"></param>
    /// <returns></returns>
    public virtual TopicMeta PublishTopic( Document document )
    {
      TopicMeta topic = LaunchTopic( document );

      Service.BoardPersister.DataProvider.AddTopic( this, topic );

      return topic;
    }


    /// <summary>
    /// 发起一个话题
    /// </summary>
    /// <param name="document"></param>
    /// <returns></returns>
    protected virtual TopicMeta LaunchTopic( Document document )
    {
      if ( !document.Meta.Saved )
        throw new ArgumentException( "不能发布未保存的文档", "document" );

      TopicMeta meta = CreateTopicMeta( document );

      int topicId = Service.TopicPersister.SaveTopic( meta );

      GeneralTopicFrame topic = new GeneralTopicFrame( Service, topicId );

      topic.LaunchedFrom( document );

      Service.TopicPersister.SaveTopic( topic );


      Service.TopicMetaCache.AddItem( meta );
      Service.TopicFrameCache.AddItem( topic );

      return meta;
    }



    /// <summary>
    /// 创建一个话题的元数据
    /// </summary>
    /// <param name="document"></param>
    /// <returns></returns>
    protected virtual TopicMeta CreateTopicMeta( Document document )
    {
      DateTime publishDate = DateTime.UtcNow;

      TopicMeta meta = new TopicMeta()
      {
        Title = document.Meta.Title,
        Launcher = document.Meta.Author,
        LaunchDate = DateTime.UtcNow
      };

      return meta;

    }


    private int _dataId;

    public int PracticalDataId
    {
      get { return _dataId; }
    }

    public override void LoadSettings( IDictionary<string, string> settings )
    {
      _dataId = int.Parse( settings["dataId"] );//UNDONE 未作合法性判断
    }


    public override IEnumerable<TopicFrame> GetTopics()
    {
      return BoardFrameDataProvider.DbUtility.ExecuteSingleColumn<int>( "SELECT Topics.ID FROM BoardFrameTopics INNER JOIN Topics ON ( BoardFrameTopics.TopicId = Topics.ID ) WHERE BoardFrameTopics.BoardId = {0} ORDER BY Topics.PublishDate DESC", PracticalDataId ).Select( topicId => Service.GetTopicFrame( topicId ) );
    }
  }
}